package com.example.biji;

import static android.view.View.GONE;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;


import android.app.AlarmManager;

import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private NoteDatabase dbHelper;

    private Context context = this;
    final String TAG = "tag";
    private FloatingActionButton btn;

    private ListView lv;

    private NoteAdapter adapter;
    private List<Note> noteList = new ArrayList<Note>();
    private Toolbar myToolbar;


    //弹出菜单
    private PopupWindow popupWindow; //弹出菜单主体
    private PopupWindow popupCover; //弹出菜单蒙版
    private ViewGroup customView; //定义菜单主体的样式
    private ViewGroup coverView; //定义菜单蒙版的样式
    private LayoutInflater layoutInflater; //用于读取样式
    private RelativeLayout main; //用于绑定主页面的样式
    private WindowManager wm; //窗口管理器
    private DisplayMetrics metrics;
    private TagAdapter tagAdapter;

    private TextView setting_text; //弹出窗口设置文本
    private ImageView setting_image; //弹出窗口设置图片

    private TextView add_tag; //增加标签按钮
    private ListView lv_tag; //标签列表
    private SharedPreferences sharedPreferences; //定义一个轻量级的存储空间

    PendingIntent pendingIntent;
    AlarmManager alarmManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




//        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        Intent intent1 = new Intent(this,ClockActivity.class);
//        pendingIntent = PendingIntent.getActivity(getApplication(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

        //向轻量级存储空间提交标签类型
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (!sharedPreferences.contains("tagListString")) {
            String s = "no tag_life_study_work_play";
            editor.putString("tagListString", s);
            editor.commit();
        }


        //
        setContentView(R.layout.activity_main);
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.lvBackground, typedValue, true);


        //绑定创建新笔记按钮
        btn = findViewById(R.id.fab);
        //绑定主页笔记按钮
        lv = findViewById(R.id.lv);

        //初始化弹出窗口
        initPopUpView();

        //将所有笔记内容转化为ListView可以接受的数据类型
        adapter = new NoteAdapter(getApplicationContext(), noteList);

        refreshListView();

        //将笔记在主页面上显示出来
        lv.setAdapter(adapter);

        //绑定工具栏
        myToolbar = findViewById(R.id.myToolbar);
        //主页面的设置按钮图标
        myToolbar.setNavigationIcon(R.drawable.ic_menu_black_24dp);

        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); //设置toolbar取代actionBar


        //当主页面的设置按钮被点击时，菜单弹出
        myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopUpView();
            }
        });

        //设置关于主页面的笔记们的点击函数
        lv.setOnItemClickListener(this);

//        lv.setOnItemLongClickListener(this);

        //跳转到编辑页面
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Log.d(TAG, "onClick: click");
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                intent.putExtra("mode", 4);
                startActivityForResult(intent, 1);
            }
        });


    }




    //点击主页面的内容
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv:
                Note curNote = (Note) parent.getItemAtPosition(position);
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                intent.putExtra("content", curNote.getContent());
                intent.putExtra("id", curNote.getId());
                intent.putExtra("time", curNote.getTime());
                intent.putExtra("mode", 3);     // MODE of 'click to edit'
                intent.putExtra("tag", curNote.getTag());
                startActivityForResult(intent, 1);      //collect data from edit
                break;

        }
    }


//    @Override
//    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//        switch (parent.getId()) {
//            case R.id.lv:
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTimeInMillis(System.currentTimeMillis());
//                calendar.add(Calendar.SECOND,3);
//                alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
//                Toast.makeText(this, "闹钟设置完成", Toast.LENGTH_SHORT).show();
//        }
//        return false;
//    }






    //设置黑夜模式
    @Override
    protected void needRefresh() {
        setNightMode();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    //初始化弹出菜单
    public void initPopUpView() {

        layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //布局存储器

        //获得弹出菜单布局
        customView = (ViewGroup) layoutInflater.inflate(R.layout.setting_layout, null);
        //获得弹出菜单蒙版布局
        coverView = (ViewGroup) layoutInflater.inflate(R.layout.setting_cover, null);

        main = findViewById(R.id.main_layout); //获得主函数页面布局

        //实例化窗口管理器
        wm = getWindowManager();
        //实例化一个度量
        metrics = new DisplayMetrics();
        //获取当前窗口的长宽
        wm.getDefaultDisplay().getMetrics(metrics);
    }



    //弹出菜单栏
    public void showPopUpView() {
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;

        //弹出菜单蒙版全屏显示，并在保持弹出菜单后面
        popupCover = new PopupWindow(coverView, width, height, false);
        //弹出菜单宽度占据百分之七十的屏幕，并显示在前端
        popupWindow = new PopupWindow(customView, (int) (width * 0.7), height, true);
        //设置背景色为白色
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

        //在主界面加载成功之后 显示弹出
        findViewById(R.id.main_layout).post(new Runnable() {
            @Override
            public void run() {
                //从左上角开始显示
                popupCover.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
                popupWindow.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);

                //绑定设置行的图标与文字
                setting_image = customView.findViewById(R.id.setting_settings_image);
                setting_text = customView.findViewById(R.id.setting_settings_text);

                //绑定分组们和增加分组标签
                lv_tag = customView.findViewById(R.id.lv_tag);
                add_tag = customView.findViewById(R.id.add_tag);

                //获取分组
                List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_"));
                tagAdapter = new TagAdapter(context, tagList, numOfTagNotes(tagList));
                lv_tag.setAdapter(tagAdapter);


                //增加tag
                add_tag.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //先做有没有达到八个分组的判断
                        if (sharedPreferences.getString("tagListString", "").split("_").length < 8) {
                            //内部类中的方法不能直接调用外部的变量，因此要用final修饰，保证数据的不变
                            final EditText et = new EditText(context);
                            new AlertDialog.Builder(MainActivity.this)
                                    .setMessage("Enter the name of tag")
                                    .setView(et)
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags

                                            String name = et.getText().toString();
                                            if (!tagList.contains(name)) {
                                                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                                                String oldTagListString = sharedPreferences.getString("tagListString", null);
                                                String newTagListString = oldTagListString + "_" + name;
                                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                                editor.putString("tagListString", newTagListString);
                                                editor.commit();
                                                refreshTagList();
                                            } else
                                                Toast.makeText(context, "Repeated tag!", Toast.LENGTH_SHORT).show();
                                        }
                                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                        } else {
                            Toast.makeText(context, "自定义的标签够多了！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                //点击tag，出现对应分组
                lv_tag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
                        //position位置的是从0开始的
                        int tag = position + 1;
                        List<Note> temp = new ArrayList<>();
                        for (int i = 0; i < noteList.size(); i++) {
                            if (noteList.get(i).getTag() == tag) {
                                Note note = noteList.get(i);
                                temp.add(note);
                            }
                        }
                        NoteAdapter tempAdapter = new NoteAdapter(context, temp);
                        lv.setAdapter(tempAdapter);
                        myToolbar.setTitle(tagList.get(position));
                        popupWindow.dismiss();
                    }
                });

                //删除tag
                lv_tag.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                        //
                        if (position > 4) {
                            new AlertDialog.Builder(MainActivity.this)
                                    .setMessage("All related notes will be tagged as \"no tag\" !")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            int tag = position + 1;
                                            for (int i = 0; i < noteList.size(); i++) {
                                                //被删除tag的对应notes tag = 1
                                                Note temp = noteList.get(i);

                                                if (temp.getTag() == tag) {
                                                    temp.setTag(1);
                                                    CRUD op = new CRUD(context);
                                                    op.open();
                                                    op.updateNote(temp);
                                                    op.close();
                                                }
                                            }

                                            List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
                                            if (tag + 1 < tagList.size()) {
                                                for (int j = tag + 1; j < tagList.size() + 1; j++) {
                                                    //大于被删除的tag的所有tag减一
                                                    for (int i = 0; i < noteList.size(); i++) {
                                                        Note temp = noteList.get(i);
                                                        if (temp.getTag() == j) {
                                                            temp.setTag(j - 1);
                                                            CRUD op = new CRUD(context);
                                                            op.open();
                                                            op.updateNote(temp);
                                                            op.close();
                                                        }
                                                    }
                                                }
                                            }

                                            //edit the preference
                                            List<String> newTagList = new ArrayList<>();
                                            newTagList.addAll(tagList);
                                            newTagList.remove(position);
                                            //将字符数组拼接成字符串
                                            String newTagListString = TextUtils.join("_", newTagList);

                                            SharedPreferences.Editor editor = sharedPreferences.edit();
                                            editor.putString("tagListString", newTagListString);
                                            editor.commit();

                                            refreshTagList();
                                            refreshPage();


                                        }
                                    }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                            return true;
                        }
                        return false;
                    }
                });

                setting_image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                    }
                });

                setting_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
                    }
                });

                coverView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        popupWindow.dismiss();
                        return true;
                    }
                });

                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        popupCover.dismiss();
                        Log.d(TAG, "onDismiss: test");
                    }
                });
            }


        });
    }

    //刷新页面
    private void refreshPage(){
        List<String> tagList1 = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
        int tag1 = 1;
        List<Note> temp = new ArrayList<>();
        for (int i = 0; i < noteList.size(); i++) {
            if (noteList.get(i).getTag() == tag1) {
                Note note = noteList.get(i);
                temp.add(note);
            }
        }

        NoteAdapter tempAdapter = new NoteAdapter(context, temp);
        lv.setAdapter(tempAdapter);
        myToolbar.setTitle(tagList1.get(0));
        popupWindow.dismiss();
    }


    //刷新tag
    private void refreshTagList() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        List<String> tagList = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
        tagAdapter = new TagAdapter(context, tagList, numOfTagNotes(tagList));
        lv_tag.setAdapter(tagAdapter);
        tagAdapter.notifyDataSetChanged();
    }

    //统计不同标签的笔记数
    public List<Integer> numOfTagNotes(List<String> noteStringList) {
        Integer[] numbers = new Integer[noteStringList.size()];
        for (int i = 0; i < numbers.length; i++) numbers[i] = 0;
        for (int i = 0; i < noteList.size(); i++) {
            numbers[noteList.get(i).getTag() - 1]++;
        }
        return Arrays.asList(numbers);
    }


    //接收startActivityForResult的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        int returnMode;
        long note_Id;
        returnMode = data.getExtras().getInt("mode", -1);
        note_Id = data.getExtras().getLong("id", 0);

        if (returnMode == 1) {  //update current note

            String content = data.getExtras().getString("content");
            String time = data.getExtras().getString("time");
            int tag = data.getExtras().getInt("tag", 1);

            Note newNote = new Note(content, time, tag);
            newNote.setId(note_Id);
            CRUD op = new CRUD(context);
            op.open();
            op.updateNote(newNote);
            noteList = op.getAllNotes();
            op.close();

            List<String> tagList1 = Arrays.asList(sharedPreferences.getString("tagListString", null).split("_")); //获取tags
            List<Note> temp = new ArrayList<>();
            for (int i = 0; i < noteList.size(); i++) {
                if (noteList.get(i).getTag() == tag) {
                    Note note = noteList.get(i);
                    temp.add(note);
                }
            }

            NoteAdapter tempAdapter = new NoteAdapter(context, temp);
            myToolbar.setTitle(tagList1.get( tag - 1 ));
            lv.setAdapter(tempAdapter);


        } else if (returnMode == 0) {  // create new note
            String content = data.getExtras().getString("content");
            String time = data.getExtras().getString("time");
            int tag = data.getExtras().getInt("tag", 1);

            Note newNote = new Note(content, time, tag);
            CRUD op = new CRUD(context);
            op.open();
            op.addNote(newNote);
            op.close();

        } else if (returnMode == 2) { // delete
            Note curNote = new Note();
            curNote.setId(note_Id);
            CRUD op = new CRUD(context);
            op.open();
            op.removeNote(curNote);
            op.close();

        } else {

        }

        refreshListView();

        super.onActivityResult(requestCode, resultCode, data);
    }


    //搜索
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);

        //search setting
        MenuItem mSearch = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) mSearch.getActionView();

        mSearchView.setQueryHint("Search");
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }


    //删除
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_clear:
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("删除全部吗？")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dbHelper = new NoteDatabase(context);
                                SQLiteDatabase db = dbHelper.getWritableDatabase();//以读写的方式打开数据库如果磁盘空间满了，数据库只能读不能写
                                db.delete("notes", null, null);
                                db.execSQL("update sqlite_sequence set seq=0 where name='notes'");
                                refreshListView();
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //刷新页面
    public void refreshListView() {

        CRUD op = new CRUD(context);
        op.open();
        // set adapter
        if (noteList.size() > 0) noteList.clear();
        noteList.addAll(op.getAllNotes());
        op.close();
        adapter.notifyDataSetChanged();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
        if (popupCover != null && popupCover.isShowing()) {
            popupCover.dismiss();
            popupCover = null;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}